package com.shimao.celnet.payment.controller;

import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCUPUser;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.service.PPayCupUserService;
import com.shimao.celnet.payment.service.PPayCustService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by XSW on 2018/10/30.
 */
@RestController
@RequestMapping(value = "/payment")
public class PayCUPPayController {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @Autowired
    private PPayService pPayService;

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private ConstantConfig constantConfig;


    @RequestMapping(value ="payCupReg",method = RequestMethod.POST)//跳转申请签约
    public Object cupReg(@RequestBody PPayCUPUser pPayCUPUser){
        JSONObject Object = new JSONObject();
        PPay pPay = new PPay();
        PPayCUPUser payCUPUser = new PPayCUPUser();
        PPayCust pPayCust = new PPayCust();
        String guid = new String();
        if(!"".equals(pPayCUPUser.getPayPaymentId())&&pPayCUPUser.getPayPaymentId()!= null){
            //根据guid查询数据库中的账单表
            pPay = pPayService.getByKey(pPayCUPUser.getPayPaymentId());
            payCUPUser = pPayCUPUser;
            guid = pPayCupUserService.getGuid();
            payCUPUser.setGuid(guid);
            payCUPUser.setPayMeruserid(pPay.getPayUserSfGuid());
            if(pPayCUPUser.getPayValiddate()!= null && pPayCUPUser.getPayValiddate() != ""){
                String validdate = String.valueOf(MyDateUtil.YmdStrToMMyy(pPayCUPUser.getPayValiddate()));
                payCUPUser.setPayValiddate(validdate);
            }
            //根据小区sfid获取商户信息
            pPayCust = getTLMessage(pPay.getEstateGuid(), FinalUtil.CUP_PAY_TYPE);
            payCUPUser.setPayCustid(pPay.getEstateGuid());
            payCUPUser.setPayNeedStatus(FinalUtil.PAY_NEED_STATUS_YES);    //绑卡后需要支付 0 不需要支付1
            payCUPUser.setPayUnbundlingstatus(FinalUtil.BANKCARD_BIND_STATUS);  //未解绑 0
            pPayCupUserService.save(payCUPUser);  //保存
            Object.put("cupGuid", guid);
        }else {
            payCUPUser =  pPayCupUserService.getByKey(pPayCUPUser.getGuid());
            String meruserid = payCUPUser.getPayMeruserid();
            if("0".equals(payCUPUser.getPayNeedStatus())){
                pPay =pPayService.getByKey(payCUPUser.getPayPaymentId());
                //根据小区sfid获取商户信息
                pPayCust = getTLMessage(pPay.getEstateGuid(),FinalUtil.CUP_PAY_TYPE);
                payCUPUser = pPayCUPUser;
                guid = pPayCupUserService.getGuid();
                payCUPUser.setGuid(guid);
                payCUPUser.setPayMeruserid(meruserid);
                payCUPUser.setPayCustid(pPay.getEstateGuid());
                payCUPUser.setPayNeedStatus(FinalUtil.PAY_NEED_STATUS_NO);    //绑卡后需要支付 0 不需要支付1  "1"
                payCUPUser.setPayUnbundlingstatus(FinalUtil.BANKCARD_BIND_STATUS);  //0：未解绑 ；1：已解绑 "0"
                if(pPayCUPUser.getPayValiddate()!= null && pPayCUPUser.getPayValiddate() != ""){
                    String validdate = String.valueOf(MyDateUtil.YmdStrToMMyy(pPayCUPUser.getPayValiddate()));
                    payCUPUser.setPayValiddate(validdate);
                }
                pPayCupUserService.save(payCUPUser);  //保存
                Object.put("cupGuid", guid);
            }else {
                payCUPUser.setPayAcctno(pPayCUPUser.getPayAcctno());
                payCUPUser.setPayAccttype(pPayCUPUser.getPayAccttype());
                payCUPUser.setPayIdno(pPayCUPUser.getPayIdno());
                payCUPUser.setPayMobile(pPayCUPUser.getPayMobile());
                payCUPUser.setPayAcctname(pPayCUPUser.getPayAcctname());
                payCUPUser.setPayUnbundlingstatus(FinalUtil.BANKCARD_BIND_STATUS);  //0：未解绑 ；1：已解绑"0"
                if(pPayCUPUser.getPayValiddate()!= null && pPayCUPUser.getPayValiddate() != ""){
                    String validdate = String.valueOf(MyDateUtil.YmdStrToMMyy(pPayCUPUser.getPayValiddate()));
                    payCUPUser.setPayValiddate(validdate);
                    payCUPUser.setPayCvv2(pPayCUPUser.getPayCvv2());
                }
                //根据小区sfid获取商户信息
                pPayCust = getTLMessage(payCUPUser.getPayCustid(),FinalUtil.CUP_PAY_TYPE);
                pPayCupUserService.update(payCUPUser);  //更新
                Object.put("cupGuid", payCUPUser.getGuid());
            }
        }
        logger.info("==================请求通联申请签约开始=====================");
        //请求通联申请签约接口
        try {
            //请求通联callout
            logger.info("========绑卡用户号："+payCUPUser.getPayMeruserid() +"=========商户号："+pPayCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.agreeapply(payCUPUser,pPayCust);
            logger.info("========通联响应参数："+map.toString());
            if("SUCCESS".equals(map.get("retcode"))){
                if("1999".equals(map.get("trxstatus"))){
                    Object.put("errorCode", map.get("trxstatus"));
                    if(map.get("thpinfo") != null && map.get("thpinfo") != ""){
                        payCUPUser.setPayThpinfo(map.get("thpinfo"));
                        pPayCupUserService.update(payCUPUser);
                    }
                }else {
                    Object.put("errorCode", map.get("trxstatus"));
                }
            }else {
                Object.put("errorCode", "4444");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Object.put("errorCode", "4444");
        }
        return Object;
    }



    @RequestMapping(value ="ResendSMS",method = RequestMethod.POST)//重发申请签约短信
    public void ResendSMS(@RequestBody PPayCUPUser pPayCUPUser){
        PPayCUPUser payCUPUser = pPayCupUserService.getByKey(pPayCUPUser.getGuid());
        //根据guid查询数据库中的账单表
        PPay pPay = pPayService.getByKey(payCUPUser.getPayPaymentId());
        //根据小区sfid获取商户信息
        PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),FinalUtil.CUP_PAY_TYPE);
        logger.info("==================重新获取申请签约短信开始=====================");
        try {
            //请求通联callout
            logger.info("========绑卡用户号："+payCUPUser.getPayMeruserid() +"=========商户号："+pPayCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.ResendSMS(payCUPUser,pPayCust);
            logger.info("========通联响应参数："+map.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value ="ResendPaySMS",method = RequestMethod.POST)//重发申请支付短信
    public void ResendPaySMS(@RequestBody PPayCUPUser pPayCUPUser){

        PPayCUPUser payCUPUser = pPayCupUserService.getByKey(pPayCUPUser.getGuid());
        //根据guid查询数据库中的账单表
        PPay pPay = pPayService.getByKey(payCUPUser.getPayPaymentId());
        //根据小区sfid获取商户信息
        PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),FinalUtil.CUP_PAY_TYPE);
        try {
            //请求通联callout
            logger.info("========绑卡用户号："+payCUPUser.getPayMeruserid() +"=========商户号："+pPayCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.ResendPaySMS(MyDateUtil.NotString(pPay.getGuid()),payCUPUser.getPayAgreeid(),payCUPUser.getPayThpinfo(),pPayCust);
            logger.info("========通联响应参数："+map.toString());
            if("SUCCESS".equals(map.get("retcode"))){
                if(map.get("thpinfo") != null && map.get("thpinfo") != ""){
                    payCUPUser.setPayThpinfo(map.get("thpinfo"));
                    pPayCupUserService.update(payCUPUser);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @RequestMapping(value ="confirmReg",method = RequestMethod.POST)//确认绑卡，并且发起支付申请
    public Object cupConfirmReg(@RequestBody PPayCUPUser pPayCUPUser){
        PPayCUPUser payCUPUser = pPayCupUserService.getByKey(pPayCUPUser.getGuid());
        payCUPUser.setSmscode(pPayCUPUser.getSmscode());
        JSONObject Object = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        Object.put("Guid",payCUPUser.getGuid());
        PPayCust pPayCust = new PPayCust();
        PPay pPay = new PPay();
        if(payCUPUser.getPayPaymentId() == null || payCUPUser.getPayPaymentId().equals("")){
            //根据商家id获取商户信息
             pPayCust = getTLMessage(payCUPUser.getPayCustid(),FinalUtil.CUP_PAY_TYPE);
        }else {
            //根据guid查询数据库中的账单表
            pPay = pPayService.getByKey(payCUPUser.getPayPaymentId());
            //根据小区sfid获取商户信息
           pPayCust = getTLMessage(pPay.getEstateGuid(),FinalUtil.CUP_PAY_TYPE);
        }
        logger.info("==================请求通联确认签约开始=====================");
        //请求通联确认签约接口
        try {
            //请求通联callout
            logger.info("========绑卡用户号："+payCUPUser.getPayMeruserid() +"=========商户号："+pPayCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.agreeconfirm(payCUPUser,pPayCust);
            logger.info("========通联响应参数："+map.toString());
            if("SUCCESS".equals(map.get("retcode"))){
                if("0000".equals(map.get("trxstatus"))){
                    Object.put("errorCode", map.get("trxstatus"));
                    payCUPUser.setPayAgreeid(map.get("agreeid"));
                    payCUPUser.setPayBankname(map.get("bankname"));
                    payCUPUser.setPayBankcode(map.get("bankcode"));
                    pPayCupUserService.update(payCUPUser);
                    if("0".equals(payCUPUser.getPayNeedStatus())){
                        //请求申请支付确认签约接口
                        logger.info("==================请求通联申请支付开始=====================");
                        logger.info("========订单号："+pPay.getGuid() +"=========商户号："+pPayCust.getCustId());
                        Map<String, String> mapPay = callOut_tlPublicService.payapply(MyDateUtil.NotString(pPay.getGuid()),payCUPUser.getPayAgreeid(),pPay.getPayAmount(),pPay.getBusinessType(),pPay.getPayRemark(),constantConfig.getTlReturnURL(),pPayCust);
                        logger.info("========通联响应参数："+mapPay.toString());
                        if("SUCCESS".equals(mapPay.get("retcode"))){ //交易成功,交易流程完成,无需支付确认
                            pPay.setUpdateDate(new Date());
                            pPay.setPayType(FinalUtil.CUP_PAY_TYPE);
                            pPay.setTrxid(mapPay.get("trxid"));
                            pPayService.update(pPay);
                            if("0000".equals(mapPay.get("trxstatus"))){
                                jsonObject.put("payCode", mapPay.get("trxstatus"));
                            }else if("1999".equals(mapPay.get("trxstatus"))){
                                jsonObject.put("payCode", mapPay.get("trxstatus"));
                                if(mapPay.get("thpinfo") != null && mapPay.get("thpinfo") != ""){
                                    payCUPUser.setPayThpinfo(mapPay.get("thpinfo"));
                                    pPayCupUserService.update(payCUPUser);
                                }
                            }else if("2000".equals(mapPay.get("trxstatus"))||"2008".equals(mapPay.get("trxstatus"))){
                                jsonObject.put("payCode", mapPay.get("trxstatus"));
                                if(mapPay.get("thpinfo") != null && mapPay.get("thpinfo") != ""){
                                    payCUPUser.setPayThpinfo(mapPay.get("thpinfo"));
                                    pPayCupUserService.update(payCUPUser);
                                }
                                jsonObject.put("payCode", mapPay.get("trxstatus"));
                                jsonObject.put("payguid", pPay.getGuid());
                            }else {
                                jsonObject.put("payCode", "4444");
                            }
                        }else {
                            jsonObject.put("payCode", "4444");
                        }
                    }else {
                        jsonObject.put("payCode", "6666");  //绑卡成功
                    }
                    Object.put("data", jsonObject);
                }else {
                    Object.put("errorCode", map.get("trxstatus"));
                }
            }else {
                Object.put("errorCode", "4444");
            }
        } catch (Exception e) {
            Object.put("errorCode", "4444");
            e.printStackTrace();
        }
        return Object;
    }

    @RequestMapping(value ="confirmPay",method = RequestMethod.POST)//发起支付确认
    public Object cupConfirmPay(@RequestBody PPayCUPUser pPayCUPUser){
        JSONObject Object = new JSONObject();
        PPayCUPUser payCUPUser = pPayCupUserService.getByKey(pPayCUPUser.getGuid());
        payCUPUser.setSmscode(pPayCUPUser.getSmscode());
        Object.put("Guid",payCUPUser.getGuid());
        //根据guid查询数据库中的账单表
        PPay pPay = pPayService.getByKey(payCUPUser.getPayPaymentId());
        //根据小区sfid获取商户信息
        PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),FinalUtil.CUP_PAY_TYPE);
        pPay.setUpdateDate(new Date());
        pPay.setPayType(FinalUtil.CUP_PAY_TYPE);
        logger.info("==================请求通联支付确认开始=====================");
        //请求申请支付确认接口
        try {
            //请求通联callout
            logger.info("========协议编号："+payCUPUser.getPayAgreeid() +"=========商户号："+pPayCust.getCustId());
            Map<String, String>   map = callOut_tlPublicService.pay(MyDateUtil.NotString(pPay.getGuid()),payCUPUser.getPayAgreeid(),payCUPUser.getSmscode(),payCUPUser.getPayThpinfo(),pPayCust);
            logger.info("========通联响应参数："+map.toString());
            if("SUCCESS".equals(map.get("retcode"))){
                if("0000".equals(map.get("trxstatus"))){
                    Object.put("errorCode", map.get("trxstatus"));
                    if(map.get("thpinfo") != null && map.get("thpinfo") != ""){
                        payCUPUser.setPayThpinfo(map.get("thpinfo"));
                        pPayCupUserService.update(payCUPUser);
                    }
                    pPay.setTrxid(map.get("trxid"));//通联唯一流水单号
                }else if("1999".equals(map.get("trxstatus"))){
                    //请求通联callout
                    logger.info("========协议编号："+payCUPUser.getPayAgreeid() +"=========商户号："+pPayCust.getCustId());
                    Map<String, String>  map1 = callOut_tlPublicService.pay(MyDateUtil.NotString(pPay.getGuid()),payCUPUser.getPayAgreeid(),payCUPUser.getSmscode(),payCUPUser.getPayThpinfo(),pPayCust);
                    logger.info("========通联响应参数："+map1.toString());
                    if("SUCCESS".equals(map1.get("retcode"))){
                        if("0000".equals(map1.get("trxstatus"))){
                            Object.put("errorCode", map1.get("trxstatus"));
                            if(map1.get("thpinfo") != null && map1.get("thpinfo") != ""){
                                payCUPUser.setPayThpinfo(map1.get("thpinfo"));
                                pPayCupUserService.update(payCUPUser);
                            }
                            pPay.setTrxid(map1.get("trxid"));//通联唯一流水单号
                        }else {
                            Object.put("errorCode", map.get("trxstatus"));
                            Object.put("payguid", pPay.getGuid());
                            pPay.setTrxid(map.get("trxid"));//通联唯一流水单号
                        }
                    }else {
                        Object.put("errorCode", "4444");
                    }
                }else{
                    Object.put("errorCode", map.get("trxstatus"));
                    Object.put("payguid", pPay.getGuid());
                    pPay.setTrxid(map.get("trxid"));//通联唯一流水单号
                }
            }else {
                Object.put("errorCode", "4444");
            }
            pPayService.update(pPay);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Object;
    }

    @RequestMapping(value ="payBindBankCard",method = RequestMethod.POST)//跳转申请签约
    public Object payBindBankCard(@RequestBody PPayCUPUser pPayCUPUser){
        JSONObject Object = new JSONObject();
        PPay pPay = new PPay();
        PPayCust pPayCust = new PPayCust();
        PPayCUPUser payCUPUser = pPayCupUserService.getByKey(pPayCUPUser.getGuid());
        if(payCUPUser.getPayPaymentId() != null){
            //根据guid查询数据库中的账单表
            pPay = pPayService.getByKey(payCUPUser.getPayPaymentId());
            //根据小区sfid获取商户信息
           pPayCust = getTLMessage(pPay.getEstateGuid(),FinalUtil.CUP_PAY_TYPE);
        }else {
            pPayCust = getTLMessage(payCUPUser.getPayCustid(),FinalUtil.CUP_PAY_TYPE);
        }
        logger.info("==================请求通联解绑开始=====================");
        //请求通联申请签约接口
        try {
            //请求通联callout
            logger.info("========绑卡用户号："+payCUPUser.getPayMeruserid() +"=========商户号："+pPayCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.unbind(payCUPUser.getPayAgreeid(),pPayCust);
            logger.info("========通联响应参数："+map.toString());
            if("SUCCESS".equals(map.get("retcode"))){
                payCUPUser.setPayUnbundlingstatus(FinalUtil.BANKCARD_UNBOUND_STATUS);  //"1"解绑
                pPayCupUserService.update(payCUPUser);
                Object.put("errorCode", "0000");

            }else {
                Object.put("errorCode", "4444");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Object.put("errorCode", "4444");

        }
        return Object;
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid ,String payType){
        return pPayCustService.getBySfGuid1(estateGuid,payType);
    }


}
